package com.zn.listener;

import com.zn.util.Constant;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

/**
 * 订阅redis topic
 */
@Configuration
public class RedisMessageListener {
    //初始化监听器
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            @Qualifier("listenerUpdateChg")
                                            MessageListenerAdapter listenerUpdateChg,
                                            @Qualifier("updateSocketInfo")
                                            MessageListenerAdapter updateSocketInfo) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //监听主力合约的变更消息
        container.addMessageListener(listenerUpdateChg, new PatternTopic(Constant.UPDATE_CHG_CHANNEL));
        //监听socket信息变更
        container.addMessageListener(updateSocketInfo, new PatternTopic(Constant.UPDATE_SOCKET_INFO_CHANNEL));
        return container;
    }
    //利用反射来创建监听到消息之后的执行方法
    @Primary
    @Bean
    MessageListenerAdapter listenerUpdateChg(RedisReceiver redisReceiver) {
        return new MessageListenerAdapter(redisReceiver, "sendUpdateChg");
    }

    @Bean
    MessageListenerAdapter updateSocketInfo(RedisReceiver redisReceiver) {
        return new MessageListenerAdapter(redisReceiver, "updateSocketInfo");
    }
}